#pragma once
#include <iostream>
#include <pthread.h>

namespace LockModule
{
    class Mutex
    {
    public:
        // 禁用拷贝构造函数和赋值构造函数
        // 如果允许拷贝构造的话多个Mutex对象同时指向一个公共资源导致出现问题
        // 也不允许拷贝赋值,避免共享或修改Mutex对象
        Mutex(const Mutex &) = delete;
        const Mutex &operator=(const Mutex &) = delete;
        Mutex()
        {
            int n = pthread_mutex_init(&_lock, nullptr);
            (void)n;
        }
        void lock()
        {
            int n = pthread_mutex_lock(&_lock);
            (void)n;
        }
        void unlock()
        {
            int n = pthread_mutex_unlock(&_lock);
            (void)n;
        }
        pthread_mutex_t *Lockptr()
        {
            return &_lock;
        }
        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_lock);
            (void)n;
        }

    private:
        pthread_mutex_t _lock;
    };
    class LockGard
    {
    public:
        LockGard(Mutex &mutex)
            : _mutex(mutex)
        {
            _mutex.lock();
        }
        ~LockGard()
        {
            _mutex.unlock();
        }

    private:
        Mutex &_mutex;
    };
}
